package com.example.musicmodule.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.util.Log;

import com.example.musicmodule.entity.Music;

import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;


/**
 * 获取本地所有音乐
 * Created by Hh。 on 2016/12/15.
 */

public class GetLocalMusicUtil {

    public static List<Music> getMusicData(Context context) {
        List<Music> musicList = new ArrayList<Music>();
        ContentResolver cr = context.getContentResolver();
        if (cr != null) {
            // 获取所有歌曲
            Cursor cursor = cr.query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null,
                    null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
            if (null == cursor) {
                return null;
            }
            if (cursor.moveToFirst()) {
                do {
                    Music m = new Music();
                    String title = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Audio.Media.TITLE));
                    String singer = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Audio.Media.ARTIST));
                    if ("<unknown>".equals(singer)) {
                        singer = "未知艺术家";
                    }
//                    String album = cursor.getString(cursor
//                            .getColumnIndex(MediaStore.Audio.Media.ALBUM));
//                    long size = cursor.getLong(cursor
//                            .getColumnIndex(MediaStore.Audio.Media.SIZE));
                    int time = cursor.getInt(cursor
                            .getColumnIndex(MediaStore.Audio.Media.DURATION));
                    String url = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Audio.Media.DATA));
                    String name = cursor
                            .getString(cursor
                                    .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                    String sbr = name.substring(name.length() - 3,
                            name.length());
                    if (sbr.equals("mp3")) {
                        m.setTitle(title);
                        m.setAuthor(singer);
                        m.setUrl(url);
                        m.setFile_duration(time/1000);
                        musicList.add(m);

                        Log.e(TAG, "getMusicData: "+url+"======================================" );
                    }
                }
                while (cursor.moveToNext());
            }
        }
        return musicList;
    }
}
